package com.apes.fn.scm.crossCompany.transfer.service;


import com.apes.fn.scm.crossCompany.transfer.model.CrossCompanyLocation;
import com.apes.fn.scm.crossCompany.transfer.repository.CrossCompanyLocationRepository;
import com.apes.framework.api.DomainService;
import com.apes.framework.jpa.spec.JpaDsl;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @ClassName: CrossCompanyLocationService
 * @Author: ljp
 * @CreateTime: 2021-07-022 16:07
 * @Description: 跨公司交易配置
 */
@Service("crossCompanyLocationService")
public class CrossCompanyLocationService extends DomainService {

    @Autowired
    private CrossCompanyLocationRepository crossCompanyLocationRepository;

    public CrossCompanyLocation create(SimpleRequest request) {
        CrossCompanyLocation crossCompanyLocation = request.getO(CrossCompanyLocation.class);
        checkCrossCompanyLocation(crossCompanyLocation);
        return crossCompanyLocationRepository.saveAndFlush(crossCompanyLocation);
    }

    public CrossCompanyLocation update(SimpleRequest request) {
        CrossCompanyLocation crossCompanyLocation = request.getO(CrossCompanyLocation.class);
        checkCrossCompanyLocation(crossCompanyLocation);
        return crossCompanyLocationRepository.saveAndFlush(crossCompanyLocation);
    }

    public CrossCompanyLocation delete(SimpleRequest request) {
        CrossCompanyLocation crossCompanyLocation = request.getO(CrossCompanyLocation.class);
        crossCompanyLocationRepository.delete(crossCompanyLocation);
        return null;
    }

    public void checkCrossCompanyLocation(CrossCompanyLocation crossCompanyLocation) {
        List<CrossCompanyLocation> all = crossCompanyLocationRepository.findAll(JpaDsl.toCriteriaByEq("company", crossCompanyLocation.getCompany()));
        all = all.stream().filter(e -> !e.getId().equals(crossCompanyLocation.getId())).collect(Collectors.toList());
        if (all.size() > 0) throw new RuntimeException("该公司已存在配置，编号:"+all.get(0).getId());
    }

}
